import { _decorator, Component, Node, v2, v3, Vec2, Vec3, Camera, EventTouch, v4, geometry, MeshRenderer, size, PhysicsSystem, rect, clamp, clamp01 } from 'cc';
import { GlobalTmpData } from '../../../Init/Config/GlobalTmpData';
import GlobalPool from '../../../Init/Tools/GlobalPool';
import { EventTypes } from '../../../Init/Managers/EventTypes';
import GlobalData from '../../../Init/Config/GlobalData';
import { GlobalEnum } from '../../../Init/Config/GlobalEnum';
import { GlobalConfig } from '../../../Init/Config/GlobalConfig';
import EventManager from '../../../Init/Managers/EventManager';
import { BasicLayer } from '../Common/Basic/BasicLayer';
import { cCollider } from '../Common/Collision98K/Collider';
import { StorageSystem } from '../../../Init/SystemStorage/StorageSystem';

const { ccclass, property } = _decorator;


@ccclass('MapLayer')
export class MapLayer extends BasicLayer {
    private _isDeath = false;
    private _isPause = false;
    // #region -------------------------------层级生命周期------------
    /**初始化 只执行一次*/
    protected init() {
        this.initTouch3D();
        this.initMapGrid();
        this.initPhysics();
    };
    /**注册通过自定义事件管理器管理的事件  */
    protected onEvents() {

    };
    /**设置状态、数据等, */
    public setData(data?: any) {
        this._isDeath = false;
        this._isPause = false;

        this.setMapGrid();

        this.setTouch();
    };
    /**重置状态、数据等，子类实现 ,注销事件*/
    public reset() {

        this.resetMapGrid();
        this.resetTouch();
        this.resetPhysics();
        GlobalPool.putAllChildren(this.node);
    }
    //游戏中 update
    public customUpdate(dt: number) {
        this.updateTouch(dt);
        if (this._isDeath || this._isPause) return;
        this.updateMapGrid(dt);
        this.updatePhysics(dt);
    }
    public customLateUpdate(dt: number) {
        this.lateUpdateMapGrid(dt);
    }

    // 复活
    onReLive() {
        this._isDeath = false;
    }
    onPauseLv() {
        this._isPause = true;
    }
    onResumeLv() {
        this._isPause = false;
    }
    // #endregion

    // #region --- 监听3d触摸
    _camera3D: Camera = null;
    // 相机位移方向
    _cameraDirec = v3();
    // 相机位置偏移
    cameraOffset = v3();

    // 实际相机位置
    cameraCurPos = v3();
    cameraTarPos = v3();
    //
    isPinch = false;
    isTouch = false;
    // 暂停触摸时间
    unTouchTime = 0;
    isUnTouchTip = false;
    touchPauseTime = 5;

    // 相机高度缩放比例
    curCameraHRate = 1;

    curCameraCfg = {
        minOffsetH: 4,
        maxOffsetH: 15,
        maxOffsetX: 4,
        maxOffsetZ: 4,
    }
    //
    _touchCount = 0;

    initTouch3D() {
        this._camera3D = GlobalData.get(GlobalEnum.GlobalDataType.Camera3D);
        this._cameraDirec.set(this._camera3D.node.position).normalize();

        this.on(EventTypes.TouchEvents.TouchStartObj, this.onTouchStart, this);
        this.on(EventTypes.TouchEvents.TouchMoveObj, this.onTouchMove, this);
        this.on(EventTypes.TouchEvents.TouchEndObj, this.onTouchEnd, this);

        // 监听手势
        this.on(EventTypes.TouchEvents.PinchGestureStart, this.onPinchGestureStart, this);
        this.on(EventTypes.TouchEvents.PinchGestureMove, this.onPinchGestureMove, this);
        this.on(EventTypes.TouchEvents.PinchGestureEnd, this.onPinchGestureEnd, this);
    }

    setTouch() {
        // 根据当前地图大小设置高度
        const mapSize = size(GlobalTmpData.CurLevelData.mapSize);
        // 根据地图尺寸缩放
        const sizeRate = mapSize.width <= GlobalConfig.mapScaleMinWidth ?
            1 : ((mapSize.width - GlobalConfig.mapScaleMinWidth) * 0.03) + 1;
        console.log('触摸 sizeRate', sizeRate);

        // 当前缩放后的配置
        this.curCameraCfg.minOffsetH = GlobalConfig.cameraCfg.minOffsetH;
        this.curCameraCfg.maxOffsetH = GlobalConfig.cameraCfg.maxOffsetH * sizeRate;
        this.curCameraCfg.maxOffsetX = GlobalConfig.cameraCfg.maxOffsetX * sizeRate;
        this.curCameraCfg.maxOffsetZ = GlobalConfig.cameraCfg.maxOffsetZ * sizeRate;

        // 初始偏移-
        this.cameraOffset.set(1.5, this.curCameraCfg.maxOffsetH * sizeRate * 0.5, 1);
        // 计算相机位置
        this.calCameraTargetPos();
        // 当前高度略低目标高度->动画效果
        const hRate = StorageSystem.getData().levelAssets.maxLv == 1 ? 1 : 0.3;
        this.cameraCurPos.set(this.cameraTarPos.x, this.curCameraCfg.maxOffsetH * sizeRate, this.cameraTarPos.z);
        // 设置相机属性
        EventManager.emit(EventTypes.CameraEvents.SetCameraPos, this.cameraCurPos);
        //
        this.isPinch = false;
        this.isTouch = false;
        this.isUnTouchTip = false;
        this.unTouchTime = 0;
        this._touchCount = 0;
    }

    resetTouch() {
        this.isPinch = false;
        this.isTouch = false;
        this.isUnTouchTip = false;
        this.unTouchTime = 0;
        this._touchCount = 0;
    }
    // 根据cameraOffset,xz计算滑动距离 y计算缩放
    calCameraTargetPos() {
        tmpP3_0.set(this._cameraDirec).multiplyScalar(this.cameraOffset.y);
        tmpP3_0.add3f(this.cameraOffset.x, 0, -this.cameraOffset.z);
        this.cameraTarPos.set(tmpP3_0);
    }

    updateTouch(dt: number) {
        // 计算目标位置
        this.calCameraTargetPos();
        // 位移插值
        this.cameraCurPos.y += (this.cameraOffset.y - this.cameraCurPos.y) * (this.isPinch ? 0.8 : 0.1);

        this.cameraCurPos.x += (this.cameraTarPos.x - this.cameraCurPos.x) * 0.5;
        this.cameraCurPos.z += (this.cameraTarPos.z - this.cameraCurPos.z) * 0.5;

        // 设置相机属性
        EventManager.emit(EventTypes.CameraEvents.SetCameraPos, this.cameraCurPos);
        // 检测触摸操作间隔
        if (!this.isTouch && !this.isUnTouchTip) {
            this.unTouchTime += dt;
            if (this.unTouchTime > this.touchPauseTime) {
                this.isUnTouchTip = true;
                // 操作提示

            }
        }
    }

    onPinchGestureStart(scale: number, e: EventTouch) {
        console.log('onPinchGestureStart', scale);
    }
    // 双手捏合手势
    onPinchGestureMove(step: number, e: EventTouch) {
        this.isPinch = true;
        this.cameraOffset.y -= step * 0.002 * this.curCameraCfg.maxOffsetH;
        this.cameraOffset.y = clamp(this.cameraOffset.y, this.curCameraCfg.minOffsetH - 0.5, this.curCameraCfg.maxOffsetH + 0.5);
        //
        this.curCameraHRate = clamp01(this.cameraOffset.y / this.curCameraCfg.maxOffsetH);
    }
    onPinchGestureEnd(scale: number, e: EventTouch) {
        this.cameraOffset.y = clamp(this.cameraOffset.y, this.curCameraCfg.minOffsetH, this.curCameraCfg.maxOffsetH);
        console.log('onPinchGestureEnd', scale);
    }
    // 重置触摸提示
    onResetTouchTip() {
        this.unTouchTime = 0;
        this.isUnTouchTip = false;
    }

    _preCameraOffset = v3();
    onTouchStart(e: EventTouch) {
        this._touchCount++;
        console.log('onTouchStart', this._touchCount);

        if (this._touchCount > 1) {
            this.isPinch = true;
            // 终止位移
            this.cameraTarPos.set(this.cameraCurPos);
            return;
        }


        this._preCameraOffset.set(this.cameraOffset);
        this.onResetTouchTip();
        this.isTouch = true;
    }
    onTouchMove(e: EventTouch) {
        if (this.isPinch) return;

        this.isTouch = true;
        e.getUILocation(tmpP2_1);
        e.getUIStartLocation(tmpP2_0);
        // 与初始点击位置的差值
        tmpP2_0.subtract(tmpP2_1);
        const dist = tmpP2_0.length();
        if (dist < 5) return;

        tmpP2_0.multiplyScalar(0.03 * this.curCameraHRate);
        this.cameraOffset.x = clamp(tmpP2_0.x + this._preCameraOffset.x, -this.curCameraCfg.maxOffsetX, this.curCameraCfg.maxOffsetX);
        this.cameraOffset.z = clamp(tmpP2_0.y + this._preCameraOffset.z, -this.curCameraCfg.maxOffsetZ, this.curCameraCfg.maxOffsetZ);
    }

    onTouchEnd(e: EventTouch) {
        this._touchCount--;
        // console.log('onTouchEnd', this.isPinch, this._touchCount);
        // 单指点击
        if (this._touchCount == 0) {
            e.getUILocation(tmpP2_0);
            e.getUIStartLocation(tmpP2_1);
            // 判断是否为点击
            const len = tmpP2_1.subtract(tmpP2_0).length();
            if (len < 5) {
                e.getLocation(tmpP2_2);
                const target: Node = this.rayCheckObj(tmpP2_2);
                if (target) {
                    // 判断点击目标

                }
            }
            this.isPinch = false;
        }

        this.isTouch = false;
    }

    private ray: geometry.Ray = geometry.Ray.create();
    // 射线检测
    private rayCheckObj(wpos: Vec2): Node {
        this._camera3D.screenPointToRay(wpos.x, wpos.y, this.ray);
        // 以下参数可选
        const mask = 0xffffffff;
        const maxDistance = 150;
        const queryTrigger = true;
        // 检测最近碰撞盒
        if (PhysicsSystem.instance.raycastClosest(this.ray, mask, maxDistance, queryTrigger)) {
            const raycastClosestResult = PhysicsSystem.instance.raycastClosestResult;
            const collider = raycastClosestResult.collider;

            return collider.node;
        }
        return null;
    }
    //#endregion

    // #region --- 外置物理引擎
    initPhysics() {
        cCollider.inst;
    }
    resetPhysics() {
        cCollider.inst.reset(); //重置复用
    }
    updatePhysics(dt) {
        cCollider.inst.update(dt);
    }

    // #endregion

    // #region --- 设置地图
    gridMap: Node = null;
    // 边缘障碍宽度
    borderWidth: number = 1;
    // 初始建筑位置
    initBuildingPosArr: Vec3[] = [];

    initMapGrid() {

    }

    setMapGrid() {
        // this.showDebug();

    }

    // ----调试----
    showDebug() {

    }

    resetMapGrid() {

    }
    updateMapGrid(dt) {

    }

    lateUpdateMapGrid(dt) {
    }

    //#endregion

    //#region --- 引导

    //#endregion
}

const tmpP2_0 = v2();
const tmpP2_1 = v2();
const tmpP2_2 = v2();
const tmpP3_0 = v3();
const tmpP3_1 = v3();
const tmpP3_2 = v3();
const tmpP3_3 = v3();
const tmpP3_4 = v3();
const tmpP3_5 = v3();
const tmpS3_0 = v3();
const tmpP4_0 = v4();
const tmpRect0 = rect();
const tmpRect1 = rect();
const tmpSize1 = size();
